import React from 'react';
import { Upload, Icon, Modal } from 'antd';
import PropTypes from 'prop-types';

/**
 {
    uid: '-1',
    name: 'xxx.png',
    status: 'done',
    url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  }
 */

class PicturesWall extends React.Component {
  static PropTypes = {
    onChange: PropTypes.func,
  }

  static defaultProps = {
    onChange: () => null,
  }

  state = {
    previewVisible: false,
    previewImage: '',
    fileList: [],
  };

  componentDidMount() {
    const fileList = this.props.value;
    let data = [];
    try {
      data = JSON.parse(fileList);
    } catch (e) {
      console.log(e);
    }

    this.setState({ // eslint-disable-line
      fileList: data,
    });
  }

  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }

  handleChange = ({ fileList }) => {
    this.setState({ fileList });
    const data = [];
    for (const item of fileList) {
      if (item.percent === 100) {
        data.push({
          uid: item.uid,
          name: item.name,
          status: 'done',
          url: '/file/1535866491632.jpg',
          uploaded: true,
        });
      } else if (item.uploaded === true) {
        data.push(item);
      }
    }
    this.props.onChange(data);
  }

  render() {
    const { previewVisible, previewImage, fileList } = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    return (
      <div className="clearfix">
        <Upload
          action="/audiorecord/uploadfile"
          accept="image/*"
          data={{
            type: 'image',
            folder: 'file',
          }}
          listType="picture-card"
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
        >
          {fileList.length >= 1 ? null : uploadButton}
        </Upload>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    );
  }
}

export default PicturesWall;
